import {
  getCurrentUser,
  getDoctors,
  getConsultations,
  sendMessage,
  getDoctorInfo,
  getUsers,
  updateConsultationStatus,
  deleteConsultation
} from '@/api/consultation'

const state = {
  currentUser: null,
  doctors: [],
  users: [],
  currentDoctor: null,
  messages: [],
  loading: false,
  error: null,
  consultations: [],
  total: 0
}

const mutations = {
  SET_CURRENT_USER(state, user) {
    state.currentUser = user
  },
  SET_DOCTORS(state, doctors) {
    state.doctors = doctors
  },
  SET_USERS(state, users) {
    state.users = users
  },
  SET_CURRENT_DOCTOR(state, doctor) {
    state.currentDoctor = doctor
  },
  SET_MESSAGES(state, messages) {
    state.messages = messages
  },
  SET_CONSULTATIONS(state, { data, total }) {
    state.consultations = data
    state.total = total
  },
  ADD_MESSAGE(state, message) {
    state.messages = [...state.messages, message];
  },
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  SET_ERROR(state, error) {
    state.error = error
  }
}

const actions = {
  // 获取当前用户信息
  async fetchCurrentUser({ commit }) {
    try {
      commit('SET_LOADING', true)
      const { data } = await getCurrentUser()
      commit('SET_CURRENT_USER', data)
      return data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 获取医生列表
  async fetchDoctors({ commit }) {
    try {
      commit('SET_LOADING', true)
      const { data } = await getDoctors()
      commit('SET_DOCTORS', data)
      return data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 获取用户列表
  async fetchUsers({ commit }) {
    try {
      commit('SET_LOADING', true)
      const { data } = await getUsers()
      commit('SET_USERS', data)
      return data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 选择医生
  async selectDoctor({ commit }, doctor) {
    try {
      // 获取最新的医生信息
      const { data } = await getDoctorInfo(doctor.id)
      commit('SET_CURRENT_DOCTOR', data)
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    }
  },

  // 获取对话消息
  async fetchMessages({ commit, state }) {
    try {
      commit('SET_LOADING', true)
      const params = {
        doctorId: state.currentDoctor?.id,
        patientId: state.currentUser.id
      }
      const { data } = await getConsultations(params)
      // 只取第一个咨询的 messages 字段，并过滤掉无内容或空白内容的消息
      const filteredMessages = (data[0]?.messages || []).filter(msg => msg.content && msg.content.trim())
      commit('SET_MESSAGES', filteredMessages)
      return filteredMessages
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 获取所有咨询记录（管理员用）
  async fetchAllConsultations({ commit }, params) {
    try {
      commit('SET_LOADING', true)
      const { data, total } = await getConsultations(params)
      commit('SET_CONSULTATIONS', { data, total })
      return { data, total }
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 发送消息
  async sendMessage({ commit, state }, message) {
    try {
      commit('SET_LOADING', true);
      // 直接将前端传来的消息对象添加到 state
      commit('ADD_MESSAGE', message); // 直接添加 message 对象

      // 调用 API 将消息发送到后端保存
      // API 调用只负责保存数据，不需要返回完整的消息对象来更新 state
      await sendMessage({ // 调用 api/consultation.js 中的 sendMessage
        doctorId: state.currentDoctor.id,
        patientId: state.currentUser.id,
        content: message.content,
        sender: message.sender,
        time: message.time // 将时间也发送给后端保存
      });

      // API 调用成功后，返回前端传递过来的 message 对象
      return message;

    } catch (error) {
      // 如果 API 调用失败，可能需要从 state 中移除刚刚添加的消息
      // 但为了简化，这里只报错，实际应用中可能需要更复杂的错误处理和状态回滚
      commit('SET_ERROR', error.message);
      // 如果 API 失败，前端已经添加到列表的消息会保留，这可能导致数据不一致，但可以先这样处理
      throw error;
    } finally {
      commit('SET_LOADING', false);
    }
  },

  // 更新咨询状态
  async updateStatus({ dispatch }, { consultationId, status }) {
    try {
      await updateConsultationStatus(consultationId, status)
      // 重新加载咨询列表
      await dispatch('fetchAllConsultations')
    } catch (error) {
      throw error
    }
  },

  // 删除咨询
  async deleteConsultation({ dispatch }, consultationId) {
    try {
      await deleteConsultation(consultationId)
      // 重新加载咨询列表
      await dispatch('fetchAllConsultations')
    } catch (error) {
      throw error
    }
  }
}

const getters = {
  canSendMessage: state => state.currentDoctor && state.currentUser,
  getDoctorById: state => id => state.doctors.find(d => d.id === id),
  getUserById: state => id => state.users.find(u => u.id === id)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 